<template>
  <a-drawer
    :title="title"
    :visible="visible"
    :destroyOnClose="true"
    :width="460"
    :body-style="{
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
      overflow: 'auto',
    }"
    @close="onClose"
  >
    <a-form layout="vertical">
      <a-row :wrap="true" :gutter="12">
        <a-col :span="24">
          <a-form-item label="公司名称" v-bind="validateInfos.company">
            <a-input
              v-model:value="formData.company"
              placeholder="请填写公司名称"
              :disabled="isDetail"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="公司简称" v-bind="validateInfos.name">
            <a-input
              v-model:value="formData.name"
              placeholder="请填写公司简称"
              :disabled="isDetail"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="纳税人识别号" v-bind="validateInfos.taxpayer_number">
            <a-input
              placeholder="请输入纳税人识别号"
              v-model:value="formData.taxpayer_number"
              :disabled="isDetail"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="所属地区" v-bind="validateInfos.area">
            <a-cascader
              v-model:value="formData.area"
              :options="areaOptions"
              :load-data="loadAreaData"
              placeholder="请选择省市区"
              change-on-select
              @change="areaSelectChange"
              :disabled="isDetail"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="联系地址" v-bind="validateInfos.address">
            <a-input
              placeholder="请输入公司联系地址"
              v-model:value="formData.address"
              :disabled="isDetail"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="状态" v-bind="validateInfos.status">
            <a-switch
              :checkedValue="0"
              :unCheckedValue="1"
              :disabled="isDetail"
              v-model:checked="formData.status"
              checked-children="开启"
              un-checked-children="关闭"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onClose"> 取消 </a-button>
        <a-button v-if="!isDetail" type="primary" @click.prevent="onSubmit" :loading="submitLoading"> 提交 </a-button>
      </a-space>
    </div>
  </a-drawer>
</template>
<script>
import {defineComponent, reactive, toRefs, computed, watch, toRaw, ref} from "vue";
import { Form, message } from "ant-design-vue";
import store from "../../../../store";
import request from "../../../../common/utils/request";
import {
  TextTip,
} from "bl-common-vue3";
const useForm = Form.useForm;
import _ from "lodash";

export default defineComponent({
  name: "AddCompany",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: 0,
    },
    isDetail: {
      type: Boolean,
      default: false,
    }
  },
  components: { TextTip },
  setup(props, { emit }) {
    const state = reactive({
      submitLoading: false,
    });
    // 省市区
    const areaOptions = ref([]);

    const title = computed(() => {
      return props.id ? props.isDetail ? "查看公司" : "编辑公司" : "添加公司";
    });

    const formData = reactive({
      company: '',
      name: '',
      taxpayer_number: '',
      area: [],
      address: '',
      status: 0,
    });
    const ruleRef = reactive({
      company: [{ required: true, message: "必填" }],
      name: [{ required: true, message: "必填" }],
      taxpayer_number: [{ required: true, message: "必选" }],
      area: [
        {
          required: true,
          validator: (rules, value) => areaValidator(value),
          trigger: "blur",
        },
      ],
      address: [{ required: true, message: "必填" }],
    });

    const areaValidator = async (value) => {
      if (!value?.length) {
        return Promise.reject("所属地区为必填项");
      }
      if (value?.length < 2) {
        return Promise.reject("所属地区至少选择两级");
      }
      return Promise.resolve();
    };

    const { resetFields, validate, validateInfos} = useForm(formData, ruleRef);

    let detail = {};
    const getCityByProvince = (province) => {
      request
        .get("/public", "/district/city_list", {
          province_id: province.value,
        })
        .then((res) => {
          if (res.list) {
            province.children = res.list.map((item) => {
              let city = {
                label: item.name,
                value: item.area_code,
                level: 2,
                isLeaf: true,
              };
              if (detail.city_id && city.value == detail.city_id) {
                selectedAreaOptions.push(city);
              }
              return city;
            });
            areaOptions.value = [...areaOptions.value];
          }
        });
    };

    // 动态加载省市信息
    const loadAreaData = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      if (targetOption.level == 1) {
        // 请求市
        getCityByProvince(targetOption);
      }
    };

    let selectedAreaOptions = [];
    // 获取省
    const getProvinceList = (provinceId) => {
      selectedAreaOptions = [];
      request.get("/public", "/district/province_list").then((res) => {
        if (res.list) {
          areaOptions.value = res.list.map((item) => {
            const provinceItem = {
              value: item.area_code,
              label: item.name,
              level: 1,
              isLeaf: false,
            };
            if (provinceId && provinceItem.value == provinceId) {
              selectedAreaOptions.push(provinceItem);
              getCityByProvince(provinceItem);
            }
            return provinceItem;
          });
        }
      });
    };


    // 监听省市区选择
    const areaSelectChange = (value, selectedOptions) => {
      selectedAreaOptions = selectedOptions;
    };

    const onSubmit = () => {
      validate().then(() => {
        let params = {
          ...toRaw(formData),
          needMsg: true,
        };
        params.province_id = selectedAreaOptions[0].value;
        params.city_id = selectedAreaOptions[1].value;
        params.district_txt = `${selectedAreaOptions[0].label},${selectedAreaOptions[1].label}`;
        delete params.area;
        let requestType = 'post';
        if (props.id) {
          // 编辑
          requestType = 'put';
          params.id = props.id;
        }
        request[requestType]("/org", '/company/orgBranch', params)
          .then((res) => {
            message.success(res.msg || "保存成功");
            state.submitLoading = false;
            emit("handleSuccess");
          })
          .catch((err) => {
            state.submitLoading = false;
          });
      });
    };


    const onClose = () => {
      emit("handleCancel");
    };

    const setModelRef = (data) => {
      for (let key in data) {
        formData[key] = data[key];
      }
    };

    const getDetail = () => {
      detail = {};
      request.get("/org", "/company/orgBranch/detail", {id: props.id}).then((res) => {
        detail = res?.detail || {};
        setModelRef({
          company: detail.company,
          name: detail.name,
          taxpayer_number: detail.taxpayer_number,
          area: detail.city_id ? [detail.province_id, detail.city_id] : [],
          address: detail?.address || '',
          status: detail?.status || 0,
        })
        getProvinceList(detail.province_id);
      });
    };

    const init = () => {
      if (props.id) {
       getDetail();
       return;
      }
      getProvinceList();
    };

    const reset = () => {
      areaOptions.value = [];
      state.submitLoading = false;
      selectedAreaOptions = [];
      detail = {};
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          resetFields();
          reset();
        }
      }
    );

    return {
      ...toRefs(state),
      formData,
      validateInfos,
      title,
      areaOptions,
      onClose,
      onSubmit,
      loadAreaData,
      areaSelectChange,
    };
  },
});
</script>
